<template>
    <div class="container">
        <el-form :model="searchForm" class="search-form" ref="searchForm" label-width="90px">
            <el-row width="100%">
                <el-col :span="6">
                    <el-form-item label="姓名：">
                        <el-input v-model.trim="searchForm.name" placeholder="姓名" clearable> </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="现居住地：">
                        <!-- <el-input v-model.trim="searchForm.currentResidence" placeholder="常住地" clearable>
            </el-input> -->
                        <el-cascader
                            ref="cascaderAddr"
                            :options="workArea"
                            :props="{ value: 'code', label: 'name', children: 'childVo', checkStrictly: true }"
                            :show-all-levels="false"
                            v-model="searchForm.currentResidenceCode"
                            placeholder="请选择现居地地"
                            @change="domicilePlaceclick"
                        >
                        </el-cascader>
                    </el-form-item>
                </el-col>
                <el-col :span="16">
                    <el-form-item label="采集时间：">
                        <el-date-picker
                            v-model="searchForm.createTimeStart"
                            type="datetime"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            :picker-options="pickerOptionsstart"
                            placeholder="选择日期"
                        >
                        </el-date-picker
                        ><span style="margin:0 10px">-</span>
                        <el-date-picker
                            v-model="searchForm.createTimeEnd"
                            type="datetime"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            :picker-options="pickerOptionsend"
                            placeholder="选择日期"
                        >
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="6" class="btn-col">
                    <div class="buttons">
                        <el-button type="primary" @click="search">查询 </el-button>
                        <el-button type="primary" @click="resetAll">重置 </el-button>
                    </div>
                </el-col>
            </el-row>
        </el-form>
        <div class="buttons">
            <el-button type="primary" @click="roteradd">添加 </el-button>
            <el-button type="primary" @click="resetdr">导入 </el-button>
            <el-button type="primary" @click="losejobresumeExport">导出 </el-button>
            <el-button type="primary" @click="losejobresumeExportdetal">导出详情 </el-button>
            <el-button type="primary" @click="resetdatel">导入详情 </el-button>
            <el-button type="primary" @click="AllDel">删除 </el-button>
        </div>
        <div class="buttons" style="margin-top:10px">
            <el-dialog title="导入" :visible.sync="dialogVisible" width="30%">
                <span>
                    <!-- <el-upload class="upload-demo" name="file" action="/zsrencai/api/sys/admin/file/upload"
            :on-success="Filesuccess" :before-upload="beforeEnclosureUpload">
            <el-button size="small" type="primary">上传新文件</el-button>
          </el-upload> -->
                    <el-upload
                        class="upload-demo"
                        ref="upload"
                        action="/zsrencai/api/sys/admin/file/upload/module"
                        name="file"
                        :on-success="Filesuccess"
                        :before-upload="beforeEnclosureUpload"
                        :data="dataup"
                        :headers="myHeaders"
                    >
                        <!-- :http-request="postPic" -->
                        <el-button slot="trigger" size="small" type="primary">点击上传</el-button>
                        <el-button type="primary" size="small" @click="templuplod">模板下载</el-button>
                    </el-upload>
                </span>
            </el-dialog>
        </div>
        <div class="buttons" style="margin-top:10px">
            <el-dialog title="导入详情" :visible.sync="dialogVisibledatel">
                <div>
                    <el-table
                        :data="tableDatadatel"
                        :span-method="arraySpanMethod"
                        style="width: 100%"
                        row-key="id"
                        border
                        lazy
                        :load="loaddatel"
                        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
                    >
                        <el-table-column prop="field1" label="导入文件" width="240"> </el-table-column>
                        <el-table-column prop="field2" label="导入时间"> </el-table-column>
                        <el-table-column prop="field3" label="导入失败人数"> </el-table-column>
                    </el-table>
                    <el-pagination
                        class="center"
                        background
                        @size-change="handleSizeChangeuplode"
                        @current-change="handleCurrentChangeuplode"
                        :current-page="searchFormuplode.page"
                        :page-sizes="[10, 30, 60, 100, 200, 300]"
                        :page-size="searchFormuplode.size"
                        layout="prev, pager, next, jumper, sizes, total"
                        :total="totaluplode"
                    ></el-pagination>
                </div>
            </el-dialog>
        </div>
        <div class="buttons" style="margin-top:10px">
            <el-dialog title="导出详情" :visible.sync="dialogExport">
                <div>
                    <el-table :data="tableDatadatelexport">
                        <el-table-column prop="fileName" label="文件名称" width="240">
                            <template slot-scope="scope">
                                <a :href="scope.row.downUrl">{{ scope.row.fileName }}</a>
                            </template>
                        </el-table-column>
                        <el-table-column prop="createTime" label="导出时间"> </el-table-column>
                        <el-table-column prop="status" label="状态">
                            <template slot-scope="scope">
                                {{ scope.row.status === 1 ? '已生成' : '生成中' }}
                            </template>
                        </el-table-column>
                        <!-- <el-table-column fixed="right" label="操作">
              <template slot-scope="scope">
                <el-button v-if="scope.row.status===1" type="text" @click="goDetailexport(scope.row)">下载</el-button>
                <span v-if="scope.row.status!==1">下载</span>
              </template>
            </el-table-column> -->
                    </el-table>
                    <el-pagination
                        class="center"
                        background
                        @size-change="handleSizeChangeuplodeexport"
                        @current-change="handleCurrentChangeuplodeexport"
                        :current-page="searchFormuplodeexport.page"
                        :page-sizes="[10, 30, 60, 100, 200, 300]"
                        :page-size="searchFormuplodeexport.size"
                        layout="prev, pager, next, jumper, sizes, total"
                        :total="totaluplodeexport"
                    ></el-pagination>
                </div>
            </el-dialog>
        </div>
        <el-table v-loading="tableLoading" :data="tableData" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column prop="name" label="姓名">
                <template slot-scope="scope">
                    {{ scope.row.name }}
                </template>
            </el-table-column>
            <el-table-column prop="idCard" label="身份证号" width="180">
                <template slot-scope="scope">
                    {{ scope.row.idCard }}
                </template>
            </el-table-column>
            <el-table-column prop="sex" label="性别">
                <template slot-scope="scope">
                    {{ scope.row.sex ? scope.row.sex : '-' }}
                </template>
            </el-table-column>
            <el-table-column prop="createTime" label="采集时间" width="150">
                <template slot-scope="scope">
                    {{ scope.row.createTime }}
                </template>
            </el-table-column>
            <el-table-column prop="currentResidence" label="现居住地" width="160px" show-overflow-tooltip>
                <template slot-scope="scope">
                    {{ scope.row.currentResidence ? scope.row.currentResidence : '-' }}
                </template>
            </el-table-column>
            <el-table-column prop="phone" label="电话号码" width="100px">
                <template slot-scope="scope">
                    {{ scope.row.phone ? scope.row.phone : '-' }}
                </template>
            </el-table-column>
            <el-table-column prop="education" label="学历" width="160px" show-overflow-tooltip>
                <template slot-scope="scope">
                    {{ scope.row.education ? scope.row.education : '-' }}
                </template>
            </el-table-column>
            <el-table-column prop="majorCategoryText" label="专业" width="200px" show-overflow-tooltip>
                <template slot-scope="scope">
                    {{ scope.row.majorCategoryText ? scope.row.majorCategoryText : '-' }}
                </template>
            </el-table-column>
            <el-table-column prop="graduateCollege" label="毕业院校" width="100px" show-overflow-tooltip>
                <template slot-scope="scope">
                    {{ scope.row.graduateCollege ? scope.row.graduateCollege : '-' }}
                </template>
            </el-table-column>
            <el-table-column prop="skillsSpecialties" label="技能及特长" width="100px" show-overflow-tooltip>
                <template slot-scope="scope">
                    {{ scope.row.skillsSpecialties ? scope.row.skillsSpecialties : '-' }}
                </template>
            </el-table-column>
            <el-table-column prop="tradeText" label="期望行业" width="180">
                <template slot-scope="scope">
                    {{ scope.row.tradeText ? scope.row.tradeText : '-' }}
                </template>
            </el-table-column>
            <el-table-column prop="hopeSalary" label="期望待遇" width="100px">
                <template slot-scope="scope">
                    {{ scope.row.hopeSalary ? scope.row.hopeSalary : '-' }}
                </template>
            </el-table-column>

            <el-table-column fixed="right" label="操作" width="200">
                <template slot-scope="scope">
                    <el-button type="text" @click="goDetail(scope.row)">查看</el-button>
                    <el-button type="text" @click="goremove(scope.row.id)">修改</el-button>
                    <el-button type="text" @click="AllDel(2, scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            class="center"
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="searchForm.page"
            :page-sizes="[10, 30, 60, 100, 200, 300, 5000]"
            :page-size="searchForm.size"
            layout="prev, pager, next, jumper, sizes, total"
            :total="total"
        ></el-pagination>
    </div>
</template>

<script>
import {
    loseJobList,
    losejobresumeDelete,
    uploadModule,
    loseJobresumeImport,
    loseUpload,
    byFileUpload,
    losejobresumeExport,
    downloadListpage,
    includeLastLevel
} from '../../../api/personal';
import bus from '../../common/bus';
export default {
    name: 'unemployed',
    data() {
        return {
            tableData: [],
            dialogVisible: false,
            dialogVisibledatel: false,
            dialogExport: false,
            multipleSelection: [],
            tableDatadatel: [],
            tableDatadatelexport: [],
            tableLoading: false,
            workArea: [],
            pickerOptionsend: { disabledDate: this.disabledDate },
            pickerOptionsstart: { disabledDate: this.disabledstartDate },
            dataup: {
                module: 'LOSE'
            },
            myHeaders: {
                Authorization: ''
            },
            searchForm: {
                page: 1,
                size: 10,
                name: '',
                currentResidenceCode: '',
                currentResidenceAddress: '',
                createTimeStart: '',
                createTimeEnd: ''
            },
            searchFormuplode: {
                page: 1,
                size: 10
            },
            searchFormuplodeexport: {
                page: 1,
                size: 10
            },
            total: 0,
            totaluplode: 0,
            totaluplodeexport: 0
        };
    },
    created() {
        this.myHeaders.Authorization = 'Bearer ' + localStorage.getItem('ad_Authorization');
        this.url = process.env.VUE_APP_URL || '';
        this.includeLastLevel();
        this.queryInPage();
    },
    // watch: {
    //   '$route.fullPath': function (val, oldVal) {
    //     this.$nextTick(() => {
    //       if (this.$route.query.auditStatus == 0 || this.$route.query.photoAuditStatus == 0) {
    //         this.searchForm.auditStatus = this.$route.query.auditStatus || ''
    //         this.searchForm.photoAuditStatus = this.$route.query.photoAuditStatus || ''
    //         this.queryInPage();
    //       }
    //     })
    //   }
    // },
    methods: {
        //列表加载
        queryInPage() {
            this.tableLoading = true;
            // let formData = new FormData();
            // formData.append('size', this.searchForm.size);
            // formData.append('page', this.searchForm.page);
            // formData.append('name', this.searchForm.name);
            // formData.append('currentResidenceCode', this.searchForm.currentResidenceCode);
            //       let domiccode = ''
            // if (this.searchForm.domicilePlaceCode !== "") {

            //   domiccode = Number(this.searchForm.domicilePlaceCode[this.searchForm.domicilePlaceCode.length - 1])

            // }
            // let condition = [
            //   {
            //     column: 'area',
            //     type: 'eq',
            //     value: domiccode
            //   },
            //   { column: "createTimeStart", "type": "dtge", "value": this.searchForm.startDate }, { column: "createTimeEnd", "type": "dtle", "value": this.searchForm.endDate }
            // ]
            let query = {
                size: this.searchForm.size,
                page: this.searchForm.page,
                name: this.searchForm.name,
                createTimeStart: this.searchForm.createTimeStart,
                createTimeEnd: this.searchForm.createTimeEnd,
                currentResidenceAddress: this.searchForm.currentResidenceAddress
            };
            if (this.searchForm.currentResidenceCode !== '') {
                query.currentResidenceCode = Number(this.searchForm.currentResidenceCode[this.searchForm.currentResidenceCode.length - 1]);
            }
            loseJobList(query).then(data => {
                if (data.success) {
                    this.tableData = data.data.records || [];
                    this.total = data.data.total || 0;
                } else {
                    this.$message.error(`${data.msg}`);
                }
                this.tableLoading = false;
            });
        },
        //查询
        search() {
            this.searchForm.page = 1;
            this.searchForm.size = 10;
            this.queryInPage();
        },
        // 选择项发生变化时
        handleSelectionChange(val) {
            console.log(val, '选中的');
            this.multipleSelection = val;
        },
        //导入
        resetdr() {
            this.dialogVisible = true;
            this.$nextTick(() => {
                this.$refs.upload.clearFiles();
            });
        },
        //上传文件之前的判断
        beforeEnclosureUpload(file) {
            console.log(file, '上传附件');
            // 文件类型错误，支持的文件格式[jpg,png,bmp,pdf,doc,docx,ppt,pptx,xls,xlsx,zip,rar,7z]
            // 获取最后一个.定位置
            let index = file.name.lastIndexOf('.');
            // 获取后缀
            let ext = file.name.substr(index + 1);
            console.log(ext, '需要的文件后缀名');
            // 判断是否包含后缀
            if (ext !== 'xlsx') {
                this.$message.error('文件类型错误，支持的文件格式xlsx');
                return false;
            }

            const isLt10M = file.size / 1024 / 1024 < 10;
            if (!isLt10M) {
                this.$message.error('上传附件大小不能超过 10M!');
                return false;
            }
        },
        //上传成功之后调用
        Filesuccess(response, file, fileList) {
            console.log(response, 'response');
            const that = this;
            that.dialogVisible = false;
            console.log(response.success, '(response.success');
            if (response.success) {
                that.$message.success('导入失业人员成功!');
                let formData = new FormData();
                formData.append('fileUrl', response.data.fileUrl);
                formData.append('fileUploadId', response.data.id);

                loseJobresumeImport(formData).then(data => {
                    if (data.success) {
                        // this.$message.success('失业人员删除成功!')
                        // this.queryInPage();
                    } else {
                        // this.$message.error(`${data.msg}`)
                    }
                });
            } else {
                this.$message.error(`${response.msg}`);
            }

            // that.form.newsFiles.push(temp);
        },
        postPic(param) {
            console.log(param, 'param');
            let formData = new FormData();
            formData.append('file', param.file);
            formData.append('module', 'LOSE');
            uploadModule(FormData).then(data => {
                if (data.success) {
                    // this.$message.success('失业人员删除成功!')
                    // this.queryInPage();
                } else {
                    this.$message.error(`${data.msg}`);
                }
            });
        },
        // 全部删除
        AllDel(num, idmult) {
            if (this.multipleSelection.length < 1 && !idmult) {
                this.$message.error('请选择需要删除的失业人员!');
            } else {
                this.$confirm('将删除选中的失业人员，是否确定删除?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                    callback: action => {
                        if (action == 'confirm') {
                            let ids = [];
                            if (num === 2) {
                                console.log(idmult, 'idmult');
                                ids.push(idmult);
                            } else {
                                console.log(this.multipleSelection, 'this.multipleSelection');
                                this.multipleSelection.map(item => {
                                    ids.push(item.id);
                                });
                            }

                            console.log(ids, 'ids');

                            losejobresumeDelete(ids.join(',')).then(data => {
                                if (data.success) {
                                    this.$message.success('失业人员删除成功!');
                                    this.searchForm.page = 1;
                                    this.queryInPage();
                                } else {
                                    this.$message.error(`${data.msg}`);
                                }
                            });
                        }
                    }
                });
            }
        },
        //导出
        losejobresumeExport() {
            // this.tableLoading = true;
            console.log(this.tableLoading, 'tableLoading');
            this.$message({
                message: '正在导出，稍后请在导出详情查看',
                type: 'success',
                duration: 6000
            });
            let quary = {};
            quary.name = this.searchForm.name;
            (quary.createTimeStart = this.searchForm.createTimeStart),
                (quary.createTimeEnd = this.searchForm.createTimeEnd),
                (quary.currentResidenceAddress = this.searchForm.currentResidenceAddress);
            if (this.searchForm.currentResidenceCode !== '') {
                quary.currentResidenceCode = Number(this.searchForm.currentResidenceCode[this.searchForm.currentResidenceCode.length - 1]);
            }
            // if (this.multipleSelection.length === 0) {
            //   this.$confirm('导出全部文件会很慢，是否继续', '提示', {
            //     confirmButtonText: '确定',
            //     cancelButtonText: '取消',
            //     type: 'warning'
            //   }).then(() => {
            //     // quary.name = this.searchForm.name
            //     // quary.currentResidence = this.searchForm.currentResidence
            //     losejobresumeExport(quary).then(data => {
            //       this.tableLoading = false;
            //       if (data.success) {
            //         this.$message.success('失业人员导出成功!')
            //         window.location.href = data.data
            //         // this.queryInPage();
            //       } else {
            //         this.$message.error(`${data.msg}`)
            //       }
            //     });
            //   }).catch(() => {
            //     this.tableLoading = false;
            //   });

            // }
            if (this.multipleSelection.length > 0) {
                let ids = [];
                this.multipleSelection.map(item => {
                    ids.push(item.id);
                });
                console.log(this.multipleSelection, 'this.multipleSelection');
                quary.id = ids.join(',');
            }
            losejobresumeExport(quary).then(data => {
                this.tableLoading = false;
                if (data.success) {
                    // this.$message.success('失业人员导出成功!')
                    // window.location.href = data.data
                    // this.queryInPage();
                } else {
                    // this.$message.error(`${data.msg}`)
                }
            });
        },
        //导出详情
        losejobresumeExportdetal() {
            this.dialogExport = true;
            let sort = [{ column: 'create_time', type: 'desc' }];
            let formData = new FormData();
            formData.append('size', this.searchFormuplodeexport.size);
            formData.append('page', this.searchFormuplodeexport.page);
            formData.append('sort', JSON.stringify(sort));

            downloadListpage(formData).then(data => {
                // this.tableLoading = false;
                if (data.success) {
                    this.tableDatadatelexport = data.data.records;
                    this.totaluplodeexport = data.data.total || 0;
                } else {
                    this.$message.error(`${data.msg}`);
                }
            });
        },
        //下载导入excl
        goDetailexport(row) {
            window.location.href = row.downUrl;
        },
        //导入详情
        resetdatel() {
            this.dialogVisibledatel = true;
            let sort = [{ column: 'create_time', type: 'desc' }];
            let formData = new FormData();
            formData.append('size', this.searchFormuplode.size);
            formData.append('page', this.searchFormuplode.page);
            formData.append('sort', JSON.stringify(sort));
            loseUpload(formData).then(data => {
                if (data.success) {
                    this.tableDatadatel = data.data.records;
                    this.totaluplode = data.data.total || 0;
                    this.tableDatadatel.map(item => {
                        if (item.field3 === '0') {
                            item.hasChildren = false;
                        } else {
                            item.hasChildren = true;
                        }
                    });

                    console.log(this.tableDatadatel, 'this.tableDatadatel');
                    // this.$message.success('失业人员删除成功!')duration
                    // this.queryInPage();
                } else {
                    this.$message.error(`${data.msg}`);
                }
            });
        },
        //添加跳转
        roteradd() {
            this.$router.push({
                path: '/unemployedadd'
            });
        },
        //选择现居地触发
        domicilePlaceclick(e, form, thsAreaCode) {
            this.$refs.cascaderAddr.dropDownVisible = false;
            if (this.searchForm.currentResidenceCode.length === 0) {
                this.searchForm.currentResidenceCode = '';
                this.searchForm.currentResidenceAddress = '';
            }
            // console.log(e, "domicilePlaceclick")
            thsAreaCode = this.$refs['cascaderAddr'].getCheckedNodes()[0].pathLabels;
            // console.log(thsAreaCode, 'thsAreaCode')
            // console.log(this.searchForm.domicilePlaceCode, 'domicilePlaceCode')
            this.searchForm.currentResidenceAddress = thsAreaCode[thsAreaCode.length - 1];
            // this.ruleForm.domicilePlaceAddress = thsAreaCode.join('')
        },

        goremove(id) {
            this.$router.push({
                name: '/unemployedadd',
                query: {
                    id: id
                }
            });
        },
        //重置
        resetAll() {
            this.searchForm = {
                page: 1,
                size: 10,
                name: '',
                currentResidenceCode: '',
                currentResidenceAddress: '',
                createTimeStart: '',
                createTimeEnd: ''
            };
            this.queryInPage();
        },
        //获取省市区
        includeLastLevel() {
            includeLastLevel().then(data => {
                if (data.success) {
                    this.workArea = data.data;
                }
            });
        },
        //导入详情合并单元格
        arraySpanMethod({ row, column, rowIndex, columnIndex }) {
            console.log(row, 'row');

            // if (rowIndex % 2 === 0) {
            //   if (columnIndex === 0) {
            //     return [1, 2];
            //   } else if (columnIndex === 1) {
            //     return [0, 0];
            //   }
            // }
            if (!row.field1) {
                if (columnIndex === 2) {
                    return [1, 3];
                } else if (columnIndex === 0 || columnIndex === 1) {
                    return [0, 0];
                }
            }
        },
        handleSizeChange(val) {
            this.searchForm.size = val;
            this.queryInPage();
        },

        handleCurrentChange(val) {
            this.searchForm.page = val;
            this.queryInPage();
        },
        handleSizeChangeuplode(val) {
            this.searchFormuplode.size = val;
            this.resetdatel();
        },

        handleCurrentChangeuplode(val) {
            this.searchFormuplode.page = val;
            this.resetdatel();
        },
        handleSizeChangeuplodeexport(val) {
            this.searchFormuplodeexport.size = val;
            this.losejobresumeExportdetal();
        },

        handleCurrentChangeuplodeexport(val) {
            this.searchFormuplodeexport.page = val;
            this.losejobresumeExportdetal();
        },
        goDetail(row) {
            bus.$emit('openTags', { fullPath: `/unemployedDetail?id=${row.id}`, meta: { title: row.name } });
        },
        //导入详情数表二级接口
        loaddatel(tree, treeNode, resolve) {
            let formData = new FormData();
            formData.append('fileUploadId', tree.id);
            byFileUpload(formData).then(data => {
                if (data.success) {
                    console.log(data.data, '    resolve()');
                    resolve(data.data);
                } else {
                    this.$message.error(`${data.msg}`);
                }
            });
        },
        templuplod() {
            window.location.href = 'https://www.zsrencai.cn/group1/M00/00/52/CkYhFV-onj2ALlSpAAA3NRAl55836.xlsx';
        },
        disabledDate(time) {
            if (this.searchForm.createTimeStart !== '') {
                return time.getTime() < new Date(this.searchForm.createTimeStart).getTime() - 1000 * 60 * 60 * 23;
            } else {
                return time.getTime() >= Date.now();
            }
        },
        disabledstartDate(time) {
            if (this.searchForm.createTimeEnd !== '') {
                return time.getTime() > new Date(this.searchForm.createTimeEnd).getTime();
            } else {
                return time.getTime() >= Date.now();
            }
        }
    },
    watch: {
        $route: function(val, oldVal) {
            console.log(val, 'val');
            this.$nextTick(() => {
                this.searchForm = {
                    page: 1,
                    size: 10,
                    name: '',
                    currentResidenceCode: '',
                    currentResidenceAddress: '',
                    createTimeStart: '',
                    createTimeEnd: ''
                };
                this.queryInPage();
            });
        }
    }
};
</script>
<style scoped>
.el-table /deep/ td {
    text-align: center;
}
.el-table /deep/ th {
    text-align: center;
}
.center {
    text-align: center;
    margin-top: 20px;
}
.btn-col {
    float: right;
    text-align: right;
}
.btn-col .el-button {
    width: 100px;
    margin-left: 20px;
}
.container /deep/ .el-upload--text {
    border: none;
    height: 40px;
    width: 90px;
    text-align: left;
    overflow: initial;
}
</style>
